package com.brillilab.service.logic.lab;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.constant.TimeConstant;
import com.brillilab.common.entity.ResponseVo;
import com.brillilab.common.utils.CodeUtil;
import com.brillilab.domain.enums.apply.LabApplyEnum;
import com.brillilab.domain.enums.lab.LabAuditStateEnum;
import com.brillilab.domain.enums.lab.LabMemberEnum;
import com.brillilab.domain.po.lab.Lab;
import com.brillilab.domain.po.lab.LabApply;
import com.brillilab.domain.po.lab.LabApplyRejectRecord;
import com.brillilab.domain.po.lab.LabMember;
import com.brillilab.domain.po.user.InviteCode;
import com.brillilab.domain.po.user.Users;
import com.brillilab.domain.vo.common.KeyValue;
import com.brillilab.domain.vo.crm.CrmUsersInfoVo;
import com.brillilab.domain.vo.lab.ApplyJoinLabVo;
import com.brillilab.domain.vo.lab.LabApplyInfoVo;
import com.brillilab.domain.vo.lab.LabAuditVo;
import com.brillilab.domain.vo.user.UserAdminInfoVo;
import com.brillilab.service.core.email.impl.EmailServiceImpl;
import com.brillilab.service.core.lab.ILabApplyRejectRecordService;
import com.brillilab.service.core.lab.ILabApplyService;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.lab.ILabService;
import com.brillilab.service.core.system.IDictService;
import com.brillilab.service.core.system.ISystemConfigService;
import com.brillilab.service.core.user.IInviteCodeService;
import com.brillilab.service.core.user.IUserInviteAuditService;
import com.brillilab.service.core.user.IUsersService;
import com.brillilab.service.logic.message.MessageLogic;
import com.brillilab.service.logic.team.TeamLogic;
import com.brillilab.service.logic.user.UserInviteAuditLogic;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.service.module.aliyun.AliYunSms;
import com.brillilab.service.module.invite.InviteSet;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.brillilab.common.utils.DateUtil.*;

@Service
@Transactional
public class LabApplyLogic {
    @Resource
    private ILabApplyService labApplyService;
    @Resource
    private ILabService labService;
    @Resource
    private IUserInviteAuditService userInviteAuditService;
    @Resource
    private IUsersService usersService;
    @Resource
    private UsersLogic usersLogic;
    @Resource
    private ILabMemberService labMemberService;
    @Resource
    private IDictService dictService;
    @Resource
    private AliYunSms aliYunSms;
    @Resource
    private MessageLogic messageLogic;
    @Resource
    private EmailServiceImpl emailService;
    @Resource
    private TeamLogic teamLogic;
    @Resource
    private ILabApplyRejectRecordService labApplyRejectRecordService;
    @Resource
    private InviteSet inviteSet;
    @Resource
    private IInviteCodeService inviteCodeService;
    @Resource
    private UserInviteAuditLogic userInviteAuditLogic;
    @Resource
    private ISystemConfigService systemConfigService;

    /**
     * 检测用户状态
     *
     * @param mobile
     * @return
     */
    public KeyValue<Integer, String> checkUserState(String mobile) {
        LabApply labApply = labApplyService.selectUser(mobile, null);
        KeyValue<Integer, String> keyValue = new KeyValue<>();
        if (labApply != null) {
            keyValue.setKey(labApply.getState());
            if (labApply.getState().equals(LabAuditStateEnum.AUDIT_PASS.getValue())) {
                keyValue.setValue("您注册的实验室已经审核通过，快去客户端登录查看吧！");
                return keyValue;
            } else if (labApply.getState().equals(LabAuditStateEnum.WAIT_AUDIT.getValue())) {
                keyValue.setValue("您注册的实验室正在审核中，请您耐心等待。");
                return keyValue;
            } else if (labApply.getState().equals(LabAuditStateEnum.WAIT_CHECK.getValue())) {
                keyValue.setValue("您已经提交申请实验室信息，请您在邮箱中点击链接验证后进行登录。");
                return keyValue;
            }
        }
        return null;
    }

    /**
     * 检测手机号是否有实验室
     *
     * @param mobile
     * @return
     */
    public ResponseVo checkIsHaveLab(String mobile) {
        LabApply labApply = labApplyService.selectUser(mobile, null);
        UserAdminInfoVo userAdminInfoVo;
//        if (labApply != null) {
//            ResponseVo failure;
//            if (labApply.getState().equals(LabApplyEnum.State.AUDIT_WAIT.getValue())) {
//                //实验室正在审核中
//                userAdminInfoVo = new UserAdminInfoVo();
//                userAdminInfoVo.setState(ResultEnum.CURRENT_PI_LAB_AUDITING.getCode());
//                userAdminInfoVo.setMessage(ResultEnum.CURRENT_PI_LAB_AUDITING.getMessage());
//                return ResponseVo.success(userAdminInfoVo, ResultEnum.CURRENT_PI_LAB_AUDITING.getMessage());
//            }
//        }
        Users userPI = usersLogic.getUser(mobile);
        if (userPI != null) {
            if (userPI.getLabId() != null) {
                Lab lab = labService.selectByOwnerId(userPI.getId());
                if (lab != null) {
                    //存在实验室，返回相关信息
                    userAdminInfoVo = new UserAdminInfoVo();
                    userAdminInfoVo.setUserId(userPI.getId());
                    userAdminInfoVo.setRealName(userPI.getName());
                    userAdminInfoVo.setLabId(lab.getId());
                    userAdminInfoVo.setLabName(lab.getName());
                    userAdminInfoVo.setLabLogo(lab.getImageUrl());
                    userAdminInfoVo.setOrgName(lab.getOrgName());
                    userAdminInfoVo.setSecOrgName(lab.getAcademy());
                    userAdminInfoVo.setState(ResultEnum.CURRENT_PI_EXIST_LAB.getCode());
                    userAdminInfoVo.setMessage(ResultEnum.CURRENT_PI_EXIST_LAB.getMessage());
                    return ResponseVo.success(userAdminInfoVo, ResultEnum.CURRENT_PI_EXIST_LAB.getMessage());
                } else {
                    Assert.isNull(userPI, "该手机号码已经注册为非PI用户，请重新确认您需加入实验室的PI手机号码！");
                }
            }
        }

        userAdminInfoVo = new UserAdminInfoVo();
        userAdminInfoVo.setState(ResultEnum.SUCCESS.getCode());
        userAdminInfoVo.setMessage("该号码尚未注册，请确认您输入的号码是否正确，如果PI号码正确请“帮助PI创建”实验室");
        return ResponseVo.success(userAdminInfoVo, "该号码尚未注册，请确认您输入的号码是否正确，如果PI号码正确请“帮助PI创建”实验室");

    }

    /**
     * 检测邮箱地址是否有实验室
     *
     * @param email
     * @return
     */
    public ResponseVo checkEmailIsHaveLab(String email) {
        Users userPI = usersLogic.getUserByEmail(email);
        UserAdminInfoVo userAdminInfoVo;
        if (userPI != null) {
            LabApply labApply = labApplyService.selectUser(userPI.getMobile(), null);
            if (labApply != null) {
                if (labApply.getState().equals(LabApplyEnum.State.AUDIT_WAIT.getValue())) {
                    //实验室正在审核中
                    userAdminInfoVo = new UserAdminInfoVo();
                    userAdminInfoVo.setState(ResultEnum.CURRENT_PI_LAB_AUDITING.getCode());
                    userAdminInfoVo.setMessage(ResultEnum.CURRENT_PI_LAB_AUDITING.getMessage());
                    return ResponseVo.success(userAdminInfoVo, ResultEnum.CURRENT_PI_LAB_AUDITING.getMessage());
                }
            }
            if (userPI.getLabId() != null) {
                Lab lab = labService.selectByOwnerId(userPI.getId());
                if (lab != null) {
                    //存在实验室，返回相关信息
                    userAdminInfoVo = new UserAdminInfoVo();
                    userAdminInfoVo.setUserId(userPI.getId());
                    userAdminInfoVo.setRealName(userPI.getName());
                    userAdminInfoVo.setLabId(lab.getId());
                    userAdminInfoVo.setLabName(lab.getName());
                    userAdminInfoVo.setLabLogo(lab.getImageUrl());
                    userAdminInfoVo.setOrgName(lab.getOrgName());
                    userAdminInfoVo.setSecOrgName(lab.getAcademy());
                    userAdminInfoVo.setState(ResultEnum.CURRENT_PI_EXIST_LAB.getCode());
                    userAdminInfoVo.setMessage(ResultEnum.CURRENT_PI_EXIST_LAB.getMessage());
                    return ResponseVo.success(userAdminInfoVo, ResultEnum.CURRENT_PI_EXIST_LAB.getMessage());
                }
            }
        }

        userAdminInfoVo = new UserAdminInfoVo();
        userAdminInfoVo.setState(ResultEnum.SUCCESS.getCode());
        userAdminInfoVo.setMessage("此手机号名下无实验室");
        return ResponseVo.success(userAdminInfoVo, "此手机号名下无实验室");

    }

    /**
     * 检测PI信息
     *
     * @param userPI
     * @return
     */
    public boolean CheckPIUser(Users userPI) {
        if (userPI != null) {
            if (userPI.getLabId() != null) {
                Lab lab = labService.selectByOwnerId(userPI.getId());
                if (lab != null) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 提交申请实验室
     *
     * @param applyInfoVo
     * @return
     */
    public LabApply submitLabApply(LabApplyInfoVo applyInfoVo) {
        LabApply labApply = labApplyService.selectByMobile(applyInfoVo.getMobile());
        if (labApply != null) {
            Assert.isTrue(labApply.getState() != 0, "您的申请正在审核中！");
            Assert.isTrue(labApply.getState() != 1, "您的申请已经通过，请勿重复提交！");
            Assert.isTrue(labApply.getState() != 3, "验证信息已经发送到您的机构邮箱，请查收邮件进行验证！");

            //审核失败再次申请，申请状态置为待审核
            if (labApply.getState().equals(2)) {
                labApply.setState(0);
            }
        }
        //首次申请
        if (labApply == null) {
            labApply = new LabApply();
            labApply.setId(0L);
        }
        BeanUtils.copyProperties(applyInfoVo, labApply);
        //labApply.setLabLogo(applyInfoVo.getLabIcon());
        if (labApply.getIsOwner() == 0) {
            //提交人非PI
            Assert.isTrue(StringUtils.isNotEmpty(labApply.getPiRealName()), "PI姓名不能为空！");
            Assert.isTrue(StringUtils.isNotEmpty(labApply.getPiMobile()), "PI手机号不能为空！");
            Assert.isTrue(StringUtils.isNotEmpty(labApply.getPiEmail()), "PI机构邮箱不能为空！");
            Assert.notNull(labApply.getDuty(), "请选择您的职务");
            Assert.isTrue(labApply.getDuty() != 0, "请选择您的职务！");
        } else if (labApply.getIsOwner() == 1) {
            //如果是申请人是PI，则赋值PI相关信息
            labApply.setPiRealName(labApply.getRealName());
            labApply.setPiMobile(labApply.getMobile());
        }

        if (StringUtils.isNotEmpty(labApply.getOrgEmail())) {
            //机构邮箱
            String orgEmail = labApply.getOrgEmail();
            labApply.setState(LabAuditStateEnum.WAIT_AUDIT.getValue());//默认为待审核
            boolean isRightEmail = checkEmailFormat(orgEmail);
            if (isRightEmail) {
                //包含学术邮箱后缀，执行邮箱验证
                String code = CodeUtil.getCode(6, "1234567890");
                //验证码
                labApply.setVerifyCode(code);
                labApply.setState(LabAuditStateEnum.WAIT_CHECK.getValue());//待验证
            }
        } else {
            if (labApply.getLabType() == null) {
                labApply.setLabType(1);//实验室类型默认为科研机构
            }
            if (labApply.getLabType() == 1) {
                //科研机构注册
                Assert.isTrue(StringUtils.isNotEmpty(labApply.getCardImg()), "请上传证件照片！");
                Assert.isTrue(StringUtils.isNotEmpty(labApply.getCertificateNo()), "证件号不能为空！");
                Assert.isTrue(labApply.getCardImg().contains(","), "证件照参数不合法，请核实！");
            } else if (labApply.getLabType() == 2) {
                //企业注册
                if (StringUtils.isNotEmpty(labApply.getRealId())) {
                    Assert.isTrue(labApply.getCardFront().contains(","), "身份证正面照参数不合法，请核实！");
                    Assert.isTrue(labApply.getCardReverse().contains(","), "身份证反面照参数不合法，请核实！");
                }
                Assert.isTrue(labApply.getOfficialLetter().contains(","), "布理岚柏认证申请公函参数不合法，请核实！");
                Assert.isTrue(labApply.getBusinessLicence().contains(","), "营业执照参数不合法，请核实！");

            }
            labApply.setState(0);
        }
        //执行申请记录插入
        //密码处理
        labApply.setPassword(DigestUtils.md5Hex(labApply.getPassword()).toUpperCase());
        labApply.setSecurityPwd(DigestUtils.md5Hex(labApply.getSecurityPwd()).toUpperCase());
        if (labApply.getId().equals(0L)) {
            labApply = labApplyService.insert(labApply);
        } else {
            //再次申请
            labApply.setUpdateTime(new Date());
            labApply.setApplyTime(new Date());
            labApply.setAuditInfo("");
            labApplyService.updateById(labApply);
        }

        //更新邀请码类型
        if (StringUtils.isNotBlank(labApply.getInviteCode())) {
            InviteCode inviteCodeByCode = inviteCodeService.getInviteCodeByCode(labApply.getInviteCode());
            if (inviteCodeByCode != null) {

                //更新邀请码为已使用
                inviteCodeByCode.setState(1);
                inviteCodeByCode.setUpdateTime(new Date());
                inviteCodeService.updateById(inviteCodeByCode);

                labApply.setInviteCodeType(inviteCodeByCode.getUseType());
                labApplyService.updateById(labApply);
            }
        }

        if (labApply.getState().equals(3)) {
            //发送邮箱验证链接
            String param = "1_" + labApply.getId() + "_" + labApply.getVerifyCode();
            String encode = Base64.getUrlEncoder().encodeToString(param.getBytes());
            encode = encode.replace("=", "");
            String url = inviteSet.getRegisterUrl() + "index.html#registerCheck?param=" + encode;
            String title = "【LabInOne】用户邮箱验证";
            String sendHtml = "";
//            "尊敬的" + labApply.getRealName() + "先生/女士，您好，请您点击链接验证您的信息：" +
//                    "<a href='" + url + "' target='_blank'>" + url + "</a>，感谢您关注布理岚柏平台。";
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("templates/emailValidateTemp.html");
            sendHtml = emailService.getEmailSender().getEmailHtml(resourceAsStream);

            //替换信息
            sendHtml = sendHtml.replace("{realName}", labApply.getRealName());
            sendHtml = sendHtml.replace("{validateUrl}", url);

            messageLogic.sendEmail(title, sendHtml, labApply.getOrgEmail());
        }

        return labApply;
    }


    /**
     * 实验室审核通过
     *
     * @param apply
     */
    public void auditPass(LabApply apply) {
        Lab lab = new Lab();
        lab.setState(1);
        lab.setName(apply.getLabName());
        lab.setOrgName(apply.getOrgName());
        lab.setOrgId(apply.getOrgId());
        lab.setAcademy(apply.getSecOrgName());
        if (StringUtils.isEmpty(apply.getLabLogo())) {
            //若实验室logo为空,设置默认头像
            lab.setImageUrl("https://labinone-public.oss-cn-hangzhou.aliyuncs.com/image/default/lab_default.png");
        } else {
            lab.setImageUrl(apply.getLabLogo());
        }
        //实验室信息初始化
        lab.setLabType(apply.getLabType());
        lab.setMaxCount(4);//默认人数上限为4

        //默认过期时间为30天
        Date expireDate = addDate(new Date(), 30);
        String dateString = dateString(expireDate, "yyyy-MM-dd 23:59:59");
        lab.setExpireDate(stringToDate(dateString, "yyyy-MM-dd HH:mm:ss"));

        //初始化实验室数据
        Lab insertLab = labService.insert(lab);
        Users users = usersLogic.getUser(apply.getMobile());
        if (users == null) {
            //用户数据初始化
            users = usersLogic.createUsersAndInsert(insertLab.getId(), apply.getMobile(), apply.getPassword(), apply.getRealName(), apply.getCertificateNo());
            //密码处理
            users.setPassword(apply.getPassword());
            users.setSecurityPwd(apply.getSecurityPwd());
            users.setEmail(apply.getOrgEmail());
            users.setCardImg(apply.getCardImg());
            usersService.updateById(users);
        }

        if (apply.getIsOwner() == 1) {
            //实验室管理员赋值
            lab.setOwnerId(users.getId());
            labService.updateById(lab);
        }

        //实验室成员信息初始化
        LabMember labMember = new LabMember();
        labMember.setLabId(insertLab.getId());
        labMember.setUserId(users.getId());
        labMember.setState(1);
        if (apply.getIsOwner() == 1) {
            //实验室管理员职务设为PI
            labMember.setDuty("PI");
        } else {
            Map<Integer, String> userDutyMap = dictService.getUserDutyMap();
            if (userDutyMap != null) {
                labMember.setDuty(userDutyMap.get(apply.getDuty()));
            }
        }
        labMember.setEntryDate(new Date());
        LabMember initLabMember = labMemberService.add(labMember);

        if (initLabMember != null && apply.getIsOwner() == 1) {
            //初始化PI小组
            teamLogic.createOwnerTeam(insertLab.getId(), users.getId());
        }

        if (apply.getIsOwner() == 0) {
            //帮PI申请，逻辑调整为PI初始化注册
            Users userPI = usersLogic.getUser(apply.getPiMobile());
            if (userPI == null) {
                String password = CodeUtil.getCode(3, "abcdefghijklmnopqrstuvwxyz") + CodeUtil.getCode(3, "1234567890");
                //String securityPwd = CodeUtil.getCode(3, "abcdefghijklmnopqrstuvwxyz")+CodeUtil.getCode(3, "1234567890");

                userPI = usersLogic.createUsersAndInsert(insertLab.getId(), apply.getPiMobile(), password, apply.getPiRealName(), "");
                if (userPI != null) {
                    //密码处理
                    userPI.setPassword(DigestUtils.md5Hex(password).toUpperCase());
                    //userPI.setSecurityPwd(DigestUtils.md5Hex(securityPwd).toUpperCase());
                    userPI.setEmail(apply.getPiEmail());
                    userPI.setCardImg(apply.getCardImg());
                    userPI.setIsChangedPwd(0);
                    usersService.updateById(userPI);

                    //实验室PI信息初始化
                    LabMember labMemberPI = new LabMember();
                    labMemberPI.setLabId(insertLab.getId());
                    labMemberPI.setUserId(userPI.getId());
                    labMemberPI.setState(1);
                    labMemberPI.setDuty("PI");
                    labMemberPI.setEntryDate(new Date());
                    labMemberService.add(labMemberPI);

                    //初始化PI小组
                    teamLogic.createOwnerTeam(insertLab.getId(), userPI.getId());

                    //实验室PI赋值
                    insertLab.setOwnerId(userPI.getId());
                    labService.updateById(insertLab);

                    //邮件通知PI注册用户信息
                    String url = inviteSet.getRegisterUrl();
                    String title = "来自【" + apply.getRealName() + "】的邀请";
                    String sendHtml = "";
//                            "尊敬的" + apply.getPiRealName() + "先生/女士，您好，" + apply.getRealName() + "为您申请的实验室已经成功，" +
//                            "登录账号：" + apply.getPiMobile() + "，登录密码：" + password + "，请您尽快登录" +
//                            "<a href='" + url + "' target='_blank'>" + url + "</a>查看，感谢您关注布理岚柏平台。";

                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("templates/initAccountInfoTemp.html");
                    sendHtml = emailService.getEmailSender().getEmailHtml(resourceAsStream);

                    //替换信息
                    sendHtml = sendHtml.replace("{realName}", apply.getPiRealName());
                    sendHtml = sendHtml.replace("{applyName}", apply.getRealName());
                    sendHtml = sendHtml.replace("{labName}", apply.getLabName());
                    sendHtml = sendHtml.replace("{loginName}", apply.getPiMobile());
                    sendHtml = sendHtml.replace("{password}", password);

                    messageLogic.sendEmail(title, sendHtml, apply.getPiEmail());

                    //帮PI申请实验室成功，短信通知PI
                    Map<String, Object> paramMap = new LinkedHashMap<>();
                    paramMap.put("PIName", apply.getPiRealName());
                    paramMap.put("ApplyName", apply.getRealName());
                    paramMap.put("OrgName", apply.getOrgName());

                    //执行短信发送
                    messageLogic.sendSmsContent(apply.getPiMobile(), aliYunSms.getHelpPIApplyLabSuccessTemplate(), paramMap);
                }
            } else {
                //实验室成员信息初始化
                LabMember labMemberPI = new LabMember();
                labMemberPI.setLabId(insertLab.getId());
                labMemberPI.setUserId(userPI.getId());
                labMemberPI.setState(1);
                labMemberPI.setDuty("PI");
                labMemberPI.setEntryDate(new Date());
                labMemberService.add(labMemberPI);

                //实验室PI赋值为：此PI手机号对应的用户ID
                insertLab.setOwnerId(userPI.getId());
                labService.updateById(insertLab);

                //初始化PI小组
                teamLogic.createOwnerTeam(insertLab.getId(), userPI.getId());

                //帮已有账号PI申请实验室成功，短信通知PI
                Map<String, Object> paramMap = new LinkedHashMap<>();
                paramMap.put("PIName", apply.getPiRealName());
                paramMap.put("applyName", apply.getRealName());
                //执行短信发送
                messageLogic.sendSmsContent(apply.getPiMobile(), aliYunSms.getHelpHaveAccountPIApplyLabSuccessTemplate(), paramMap);
            }
        }

        //审核通过，发送“申请创建实验室审核通过”短信
        Map<String, Object> paramMap = new LinkedHashMap<>();
        paramMap.put("realName", apply.getRealName());
//        paramMap.put("applyDate", dateString(apply.getCreateTime(), "yyyy-MM-dd"));
//        paramMap.put("labName", apply.getLabName());
//        paramMap.put("expireDate", dateString(expireDate, "yyyy-MM-dd"));
        //执行短信发送
        messageLogic.sendSmsContent(apply.getMobile(), aliYunSms.getApplyCreateLabAuditPassTemplate(), paramMap);

        //试用实验室过期定时任务
//        labService.createLabExpireJobs(lab);
    }

    /**
     * 审核实验室
     *
     * @param labAuditVo
     * @param crmUsersInfoVo
     * @return
     */
    public ResponseVo auditLab(LabAuditVo labAuditVo, CrmUsersInfoVo crmUsersInfoVo) {
        LabApply labApply = labApplyService.selectById(labAuditVo.getApplyId());
        Assert.notNull(labApply, "实验室申请信息不存在，请核实！");

        labApply.setState(labAuditVo.getApplyState());
        labApply.setAuditTime(new Date());
        labApply.setUpdateTime(new Date());
        labApply.setAuditInfo(labAuditVo.getAuditInfo());
        labApply.setOperator(crmUsersInfoVo.getId());

        boolean b = labApplyService.updateById(labApply);
        if (b) {
            //执行审核通过的逻辑处理
            if (labAuditVo.getApplyState().equals(1)) {
                //帮PI申请
                if (labApply.getIsOwner() == 0) {
                    //检测PI手机号是否存在实验室且为PI
                    Users userPI = usersLogic.getUser(labApply.getPiMobile());
                    boolean isHaveLab = CheckPIUser(userPI);
                    if (!isHaveLab) {
                        //PI手机号存在实验室，申请人执行加入实验室
                        Lab lab = labService.selectByOwnerId(userPI.getId());
                        if (lab != null) {
                            return autoApplyJoinLab(labApply, lab.getId());
                        }
                    }
                    auditPass(labApply);
                } else {
                    //创建实验室
                    auditPass(labApply);
                }
                return ResponseVo.success("审核通过");
            } else if (labAuditVo.getApplyState().equals(2)) {
                //审核未通过，录入拒绝记录
                LabApplyRejectRecord labApplyRejectRecord = new LabApplyRejectRecord();
                labApplyRejectRecord.setApplyId(labApply.getId());
                labApplyRejectRecord.setAuditInfo(labAuditVo.getAuditInfo());
                labApplyRejectRecord.setOperatorId(crmUsersInfoVo.getId());
                labApplyRejectRecord.setOperatorName(crmUsersInfoVo.getRealName());
                labApplyRejectRecord.setApplyTime(labApply.getApplyTime());
                labApplyRejectRecordService.insert(labApplyRejectRecord);

                //更新邀请码使用状态
                if (StringUtils.isNotBlank(labApply.getInviteCode())) {
                    InviteCode inviteCodeByCode = inviteCodeService.getInviteCodeByCode(labApply.getInviteCode());
                    if (inviteCodeByCode != null) {
                        //恢复邀请码为未使用状态
                        inviteCodeByCode.setState(0);
                        inviteCodeByCode.setUpdateTime(new Date());
                        inviteCodeService.updateById(inviteCodeByCode);
                    }
                }

                //审核未通过，发送“申请创建实验室审核未通过”短信
                Map<String, Object> paramMap = new LinkedHashMap<>();
                paramMap.put("realName", labApply.getRealName());
                paramMap.put("failReason", labApply.getAuditInfo());
//                String formatStr = new SimpleDateFormat("yyyy-MM-dd").format(labApply.getCreateTime());
//                paramMap.put("applyDate", formatStr);
                //执行短信发送
                messageLogic.sendSmsContent(labApply.getMobile(), aliYunSms.getApplyCreateLabNotAdoptedTemplate(), paramMap);
            }
        } else {
            return ResponseVo.failure("操作失败！");
        }
        return ResponseVo.success("操作成功");
    }

    /**
     * 检测申请实验室邮箱验证码
     *
     * @param id
     * @param code
     * @return
     */
    public ResponseVo checkLabApplyCode(Long id, String code) {
        LabApply labApply = labApplyService.selectById(id);
        Assert.notNull(labApply, "无此申请实验室记录！");
        if (labApply.getState().equals(1)) {
            return ResponseVo.success("Success", "您已成功申请了实验室，请您在客户端登录。");
        }
        Assert.isTrue(labApply.getState() != 0, "您的申请正在审核中！");
        Assert.isTrue(labApply.getState() != 2, "您的申请未通过，请核实信息重新提交！");
        Assert.isTrue(labApply.getState() != 4, "您的申请已转为加入实验室！");
        Assert.isTrue(labApply.getVerifyCode().equals(code), "验证码不正确！");
        //申请时间是否超过三天
        boolean isExpire = (new Date().getTime() - labApply.getApplyTime().getTime()) / 1000 < TimeConstant.THREE_DAYS;

        if (!isExpire) {
            ResponseVo failure;
            failure = ResponseVo.failure(ResultEnum.VERIFY_CODE_EXPIRE.getMessage());
            failure.setCode(ResultEnum.VERIFY_CODE_EXPIRE.getCode());
            return failure;
        }

        //验证成功，执行实验室审核通过处理
        labApply.setState(1);
        labApply.setAuditTime(new Date());
        labApply.setUpdateTime(new Date());

        boolean b = labApplyService.updateById(labApply);
        Assert.isTrue(b, "验证失败！");

        if (labApply.getIsOwner() == 1) {
            Users userPI = usersLogic.getUser(labApply.getMobile());
            boolean isHaveLab = CheckPIUser(userPI);
            LabApply labApplyRecord = labApplyService.selectUserByPIMobile(labApply.getMobile(), LabAuditStateEnum.AUDIT_PASS.getValue());
            if (labApplyRecord != null) {
                String tips = String.format("尊敬的用户您好，%s已经为您申请了实验室，初始账号信息已发送到您的机构邮箱，您可以直接使用账号信息进行登录", labApplyRecord.getRealName());
                Assert.isTrue(isHaveLab, tips);
            }
        }

        //帮PI申请
        if (labApply.getIsOwner() == 0) {
            //检测PI手机号是否存在实验室
            Users userPI = usersLogic.getUser(labApply.getPiMobile());
            boolean isHaveLab = CheckPIUser(userPI);
            if (!isHaveLab) {
                //PI手机号存在实验室，申请人执行加入实验室
                Lab lab = labService.selectByOwnerId(userPI.getId());
                if (lab != null) {
                    return autoApplyJoinLab(labApply, lab.getId());
                }
            }
            //PI手机号不存在实验室，执行审核通过流程
            auditPass(labApply);
        } else {
            //执行审核通过的逻辑处理
            auditPass(labApply);
        }

        return ResponseVo.success("SUCCESS", "您已成功申请了实验室，请您在客户端登录。");
    }

    /**
     * 检测邮箱是否为学术结构邮箱
     *
     * @param email
     * @return
     */
    public boolean checkEmailFormat(String email) {
        return systemConfigService.checkEmailFormat(email);
    }

    /**
     * 自动执行申请加入实验室
     *
     * @param apply
     * @param labId
     * @return
     */
    public ResponseVo autoApplyJoinLab(LabApply apply, Long labId) {
        ApplyJoinLabVo applyJoinLabVo = new ApplyJoinLabVo();
        BeanUtils.copyProperties(apply, applyJoinLabVo);
        applyJoinLabVo.setLabId(labId);

        Users user = usersLogic.getUser(apply.getMobile());
        if (user != null) {
            //检测用户是否已经加入当前实验室
            if (user.getLabId() != null && user.getLabId() > 0) {
                ResponseVo failure;
                LabMember labMember = labMemberService.selectMember(applyJoinLabVo.getLabId(), user.getId());
                if (labMember != null && labMember.getState().equals(LabMemberEnum.State.STATE_IN.getValue())) {
                    //提示已加入当前实验室
                    failure = ResponseVo.failure(ResultEnum.USER_EXIST_CURRENT_LAB.getMessage());
                    failure.setCode(ResultEnum.USER_EXIST_CURRENT_LAB.getCode());
                    return failure;
                }
            }
            //已注册用户登录密码和数据密码赋值为空字符
            applyJoinLabVo.setPassword("");
            applyJoinLabVo.setSecurityPwd("");
        }

        //申请实验室转为加入实验室
        apply.setState(LabAuditStateEnum.TURN_JOIN_LAB.getValue());
        labApplyService.updateById(apply);

        //更新邀请码使用状态
        if (StringUtils.isNotBlank(apply.getInviteCode())) {
            InviteCode inviteCodeByCode = inviteCodeService.getInviteCodeByCode(apply.getInviteCode());
            if (inviteCodeByCode != null) {
                //恢复邀请码为未使用状态
                inviteCodeByCode.setState(0);
                inviteCodeByCode.setUpdateTime(new Date());
                inviteCodeService.updateById(inviteCodeByCode);
            }
        }

        return userInviteAuditLogic.autoApplyJoinLab(applyJoinLabVo);
    }

}
